package com.common.aop;

import com.common.annotation.Monitor;
import com.common.exception.UnloginException;
import com.modules.log.dao.LogMonitorDao;
import com.modules.log.entity.LogMonitorEntity;
import com.shiro.UserPrincipal;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class MonitorAop {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LogMonitorDao monitorFunctionDao;

    //jp.getSignature().getDeclaringTypeName() 包名
    //jp.getSignature().getName() 方法名
    //jp.getArgs()  方法参数

    @Around("@annotation(monitor)")
    public Object before(ProceedingJoinPoint jp, Monitor monitor) throws Throwable {
        UserPrincipal pri = null;
        try{
            pri = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
            if(pri==null)
                throw new UnloginException();
        }catch (Exception e){
            throw new UnloginException();
        }
        //监控具体实现类
        LogMonitorEntity moni = new LogMonitorEntity();
        moni.setUserId(pri.getUserId());
        moni.setPackageName(jp.getSignature().getDeclaringTypeName());
        moni.setFunctionName(jp.getSignature().getName());
        moni.setParam(Arrays.toString(jp.getArgs()));
        moni.setCreateTime(new Date());
        monitorFunctionDao.insert(moni);
        return jp.proceed();
    }
}
